package com.itistimetothink.networkdata;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;

public class ImageFromInternet {
	Bitmap image;
	
	
	public Drawable DrawableFromUrl(String url) throws IOException {
	    Bitmap x;
	    url ="http://trailxzy.knowithk.com/"+url;
	    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
	    connection.connect();
	    InputStream input = connection.getInputStream();

	    x = BitmapFactory.decodeStream(input);
	    return new BitmapDrawable(x);
	}
	
	
//	public Bitmap BitmapFromUrl(String url) throws IOException {
//	    Bitmap x;
//	    url ="http://trailxzy.knowithk.com/"+url;
//	    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
//	    connection.connect();
//	    InputStream input = connection.getInputStream();
//
//	    x = BitmapFactory.decodeStream(input);
//	    return x;
//	}
	
	public Bitmap BitmapFromUrl(String url) throws IOException {
	    Bitmap x;
	    url ="http://trailxzy.knowithk.com/"+url;
	    new DownloadImageTask(url).execute(url);
        Log.e("Error", url);
	    x = image;
        return x;
	}
	
	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
	    String url;

	    public DownloadImageTask(String url) {
//	        this.bmImage = bmImage;
	    	this.url = url;
	    }

	    protected Bitmap doInBackground(String... urls) {
	        String urldisplay = urls[0];
	        urldisplay = url;
	        Bitmap mIcon11 = null;
	        try {
	    	    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
	    	    connection.connect();
	    	    InputStream input = connection.getInputStream();
	    	    mIcon11 = BitmapFactory.decodeStream(input);
	        } catch (Exception e) {
	            Log.e("Error", e.getMessage());
	            e.printStackTrace();
	        }
	        return mIcon11;
	    }

	    protected void onPostExecute(Bitmap result) {
//	        bmImage.setImageBitmap(result);
	    	image = result;
	    }
	}
}
